/*
 * 表单控制器
 */
var app = angular.module('myApp', ['angularFileUpload', 'moment-picker']);

/*
 * 自定义通用控制器，若无定义，页面会报错
 */
app.controller('formSelfCtrl', ['$scope', '$http', function FormSelfController($scope, $http){}]);

/*
 * 子列表控制器，若无定义，页面会报错
 */
app.controller('subGridCtrl', ['$scope', '$http', function SubGridController($scope, $http){}]);

app.config(['momentPickerProvider', function (momentPickerProvider) {
    momentPickerProvider.options({
        locale:"zh-cn",
        today: true
    });
}])
.controller('fromCtrl', ['$scope', '$http', 'FileUploader', FormController]);

function FormController($scope, $http, FileUploader){
	
	console.log(dto);
	$scope.form = {checked: false}; // 表单是否已验证
	$scope.saveBtn = dto.saveBtn; // 保存按钮
	$scope.flowPassBtn = dto.flowPassBtn; // 流转按钮
	$scope.flowRefuseBtn = dto.flowRefuseBtn; // 退回按钮
	$scope.flowInitBtn = dto.flowInitBtn; // 驳回按钮
	$scope.flowLogBtn = dto.flowLogBtn; // 流程跟踪
	$scope.deleteBtn = dto.deleteBtn; // 删除按钮
	$scope.rows = dto.rows; // 表单字段数组
	$scope.footer = dto.footer; // 底部数据
	$scope.valueMap = dto.valueMap; // 值MAP
	$scope.MAP_DICT = MAP_DICT; // 字典MAP
	$scope.URL_UPLOAD = 'https://file.mini-ease.com/api/outer/upload/uploadForERP_1_0'; // 文件上传路径
	$scope.subGrid = {
			'sonlist': [], // 子列表数据数组
			'ys_form_sonlist_checkbox_all': false // 子列表全选状态
	};
	
	/*
	 * 单选弹出框数据数组初始置为空
	 */
	$scope.radio = {
			rows: [],
			pagination: {
				'currentSize': 50,
				'currentPage': 1,
				'optionArr': [{'size': 50, 'name':'每页50条'}, {'size': 100, 'name':'每页100条'}, {'size': 500, 'name':'每页500条'}, {'size': 9999, 'name':'每页1W条'}],
				'totalPage': 0,
				'totalNum': 1,
				'pagerArr': [{'num': 1},{'num': 2},{'num': 3},{'num': 4},{'num': 5}]
			}
	};
	
	/*
	 * 多选弹出框数据数组初始置为空
	 */
	$scope.checkbox = {
			rows: [],
			pagination: {
				'currentSize': 50,
				'currentPage': 1,
				'optionArr': [{'size': 50, 'name':'每页50条'}, {'size': 100, 'name':'每页100条'}, {'size': 500, 'name':'每页500条'}, {'size': 9999, 'name':'每页1W条'}],
				'totalPage': 0,
				'totalNum': 1,
				'pagerArr': [{'num': 1},{'num': 2},{'num': 3},{'num': 4},{'num': 5}]
			},
			afterSelectDatas:function(rowsSelected) {console.log(111);}
	};
	
	/*
	 * 多文件弹出框数据数组初始置为空
	 */
	$scope.multy = {
			rows: []
	};
	
	/*
	 * 确认弹出框
	 */
	$scope.confirm = {
	}
	
	//重写toFixed方法
	$scope.toFixed = function(number, precision) {
		if (Number.isInteger(Number(number))) {
			return number;
		}
		number = Math.round(+number + 'e' + precision) / Math.pow(10, precision) + '';
		let s = number.split('.');
		if ((s[1] || '').length < precision) {
			s[1] = s[1] || '';
			s[1] += new Array(precision - s[1].length).fill('0').join('');
		}
		return s.join('.');
	}
	
	/*
	 * 发送POST请求
	 */
	$scope.post = function(url, data, callback) {

		$http.post(url, {}, {params: data})
		.success(function (response) {
			if(response.code == 0) {
				console.log(response);
				$scope.radio.conditions = response.data.conditions; // 查询条件数组
				$scope.radio.colArr = response.data.colGrids; // 字段数组
				$scope.radio.pathGridRequest = response.data.pathGridRequest; // 弹出框数据请求路径
				$scope.radio.loadModalRadioGrid(1);
				
				$scope.radio.bsObj.show();
			}
		});
	}
	
	/*
	 * 主表单值发生变化
	 */
	$scope.changeValueMap = function(field) {
		console.log('---方法可重写----', field);
	}
	
	/*
	 * 主表单值发生变化
	 */
	$scope.changeValueMapOfSwitch = function(field) {
		console.log('---方法可重写----', field);
		$scope.valueMap[field] = ($scope.valueMap[field] == 0 ? 1 : 0);
	}
	
	// 初始化单图上传
    var uploader = $scope.uploaderImg = new FileUploader({
        url: $scope.URL_UPLOAD,
        autoUpload: true,
        onBeforeUploadItem: function(item) {
        	console.log(item);
    		layer.load(1, {shade: [0.5,'#000000']});
        },
        onSuccessItem: function(fileItem, response, status, headers) {
        	console.log(fileItem, response, status, headers);
        	if (response.code == 0) {
        		$scope.valueMap[fileItem.ysfield] = response.data.filePath;
    		}
        },
        onCompleteAll: function() {
    		layer.closeAll();
        }
    });
	
	// 初始化单文件上传
    var uploader = $scope.uploaderSingleFile = new FileUploader({
        url: $scope.URL_UPLOAD,
        autoUpload: true,
        onBeforeUploadItem: function(item) {
    		layer.load(1, {shade: [0.5,'#000000']});
        },
        onSuccessItem: function(fileItem, response, status, headers) {
        	if (response.code == 0) {
        		$scope.valueMap[fileItem.ysfield] = response.data.filePath;
    		}
        },
        onCompleteAll: function() {
    		layer.closeAll();
        }
    });
    
    // 查看原图
    $scope.showOriginImg = function(url) {
        window.open(url);
    }
    
    // 查看原文件
    $scope.showOriginFile = function(url) {
        window.open(url);
    }
	
	if(dto.subGridConfig2) {
		$scope.hasSubGrid = true;
	} else {
		$scope.hasSubGrid = false;
	}
	
	console.log('-------$scope.subGrid------------', $scope.subGrid);
	if($scope.hasSubGrid) {
		$scope.subGrid.buttonArr = dto.subGridConfig2.buttonArr; // 子列表按钮数组
		$scope.subGrid.colGridArr = dto.subGridConfig2.colGridArr; // 子列表字段数组
		$scope.gridId = dto.subGridConfig2.gridId;
		$scope.subGrid.sonlist = dto.subGridConfig2.sonlist; // 子列表数据数组
		
	}
	
	/*
	 * 子列表全选或反选
	 */
	$scope.subGrid.checkAllSubGrid = function() {
		console.log('---------$scope.subGrid.ys_form_sonlist_checkbox_all--------------', $scope.subGrid.ys_form_sonlist_checkbox_all);

		for(var i = 0; i < $scope.subGrid.sonlist.length; i++) {
			$scope.subGrid.sonlist[i]['ys_form_sonlist_checkbox'] = $scope.subGrid.ys_form_sonlist_checkbox_all;
		}
	}
	
	/*
	 * 子列表批量删除
	 */
	$scope.subGrid.deleteBatch = function() {
		var datas = [];
		for (var i = 0; i < $scope.subGrid.sonlist.length; i++) {
        	var data = $scope.subGrid.sonlist[i];
        	if(data['ys_form_sonlist_checkbox'] == true) {
        		continue;
        	} else {
        		datas.push(data);
        	}
		}
    	$scope.subGrid.sonlist = datas;
	}
	
	/*
	 * 文本框变动
	 */
	$scope.subGrid.textChange = function(row, field) {
		console.log('row---', row);
		console.log('field---', field);
	}
	
	/*
	 * 单元格点击
	 */
	$scope.subGrid.cellClick = function(row, field) {
		console.log('row---', row);
		console.log('field---', field);
	}
	
	/*
	 * 数字框变动
	 */
	$scope.subGrid.numberChange = function(row, field) {
		console.log('row---', row);
		console.log('field---', field);
	}
	
	/*
	 * 输入框点击事件(可重写)
	 */
	$scope.doClickOnItem = function(field) {
		console.log('---输入框点击事件(可重写)---');
	}
	
	/*
	 * 显示单选弹出框
	 * modalKey 弹出框唯一KEY
	 * type 类型，1表单用2子列表用3其它
	 * code 关联的字段编码
	 * subIndex 所在的子列表序号
	 */
	$scope.showModalRadio = function(modalKey, type, code, subIndex, conditionsDefault) {
		$scope.radio.type = type;
		$scope.radio.code = code;
		$scope.radio.subIndex = subIndex;
		if(modalKey == undefined || modalKey == null || modalKey == '') {
			layer.msg('单选弹出框KEY值尚未配置');
			return;
		}
		if(type == 2 && (subIndex == undefined || subIndex == null)) {
			layer.msg('子列表所在行号尚未配置');
			return;
		}
		$scope.radio.bsObj = new bootstrap.Modal(document.getElementById('modal_radio'), {
			keyboard: false
		});
		
		var res = MAP_MODAL[modalKey];
		console.log(modalKey);
		console.log(res);
		$scope.radio.conditions = res.conditions; // 查询条件数组
		// 处理默认条件
		if(conditionsDefault) {
			for (var i = 0; i < conditionsDefault.length; i++) {
				var conditionDefault = conditionsDefault[i];
				for (var j = 0; j < $scope.radio.conditions.length; j++) {
					if (conditionDefault['code'] == $scope.radio.conditions[j]['code']) {
						$scope.radio.conditions[j]['value'] = conditionDefault['value'];
					}
				}
			}
		}
		
		$scope.radio.colArr = res.colGrids; // 字段数组
		$scope.radio.pathGridRequest = res.pathGridRequest; // 弹出框数据请求路径
		$scope.radio.loadModalRadioGrid(1);
		
		$scope.radio.bsObj.show();
	}
	
	/*
	 * 显示复选弹出框
	 * modalKey 弹出框唯一KEY
	 * ukey 数据主键字段名，如：id
	 * listUkey 已选中的主键数组，用,隔开，示例：'1,2,3,4,5'
	 * conditionsDefault 默认搜索条件，格式如：[{code: 'vgsbm', value: 'GS0001'}]
	 */
	$scope.showModalCheckBox = function(modalKey, ukey, listUkey, conditionsDefault) {
		if(modalKey == undefined || modalKey == null || modalKey == '') {
			layer.msg('多选弹出框KEY值尚未配置');
			return;
		}
		if(ukey == undefined || ukey == null || ukey == '') {
			layer.msg('多选弹出框主键字段名尚未配置');
			return;
		}
		$scope.checkbox.ukey = ukey;
		$scope.checkbox.bsObj = new bootstrap.Modal(document.getElementById('modal_checkbox'), {
			keyboard: false
		});
		
		var res = MAP_MODAL[modalKey];
		$scope.checkbox.conditions = res.conditions; // 查询条件数组
		// 处理默认条件
		if(conditionsDefault) {
			for (var i = 0; i < conditionsDefault.length; i++) {
				var conditionDefault = conditionsDefault[i];
				for (var j = 0; j < $scope.checkbox.conditions.length; j++) {
					if (conditionDefault['code'] == $scope.checkbox.conditions[j]['code']) {
						$scope.checkbox.conditions[j]['value'] = conditionDefault['value'];
					}
				}
			}
		}
		
		$scope.checkbox.colArr = res.colGrids; // 字段数组
		$scope.checkbox.pathGridRequest = res.pathGridRequest; // 弹出框数据请求路径
		$scope.checkbox.loadModalCheckboxGrid(1);
		
		$scope.checkbox.loadModalCheckboxRight(listUkey);
		
		$scope.checkbox.bsObj.show();
	}
	
	/*
	 * 弹出多选框自定义方法(可重写)
	 */
	$scope.showModalCheckBoxSelf = function(row, code) {
		console.log('-------row---------', row);
		console.log('-------code---------', code);
	}
	
	/*
	 * 显示多文件弹出框
	 * sourceId 来源ID
	 * sourceType 来源类型，如：1
	 * sourceCode 来源编码，如：'annoeFile'
	 */
	$scope.showModalMulty = function(sourceId, sourceType, sourceCode) {
		if(sourceId == undefined || sourceId == null || sourceId == '') {
			layer.msg('多文件弹出框原始ID尚未配置');
			return;
		}
		if(sourceType == undefined || sourceType == null || sourceType == '') {
			layer.msg('多文件弹出框原始类型尚未配置');
			return;
		}
		if(sourceCode == undefined || sourceCode == null || sourceCode == '') {
			layer.msg('多文件弹出框原始编码尚未配置');
			return;
		}
		$scope.multy.sourceId = sourceId;
		$scope.multy.sourceType = sourceType;
		$scope.multy.sourceCode = sourceCode;
		$scope.multy.bsObj = new bootstrap.Modal(document.getElementById('modal_multy'), {
			keyboard: false
		});

		$scope.multy.loadModalMulty();
		
		$scope.multy.bsObj.show();
	}
	
	/*
	 * 单选弹出框选中数据后的操作(自定义)
	 */
	$scope.doSelectRadioBySelf = function(data) {
		console.log('单选框特殊回调---doSelectRadioBySelf---', data);
	}
	
	/*
	 * 确认框
	 */
	$scope.showModalConfirm = function(config) {
		$scope.confirm.tip = config.tip;
		$scope.confirm.ok = config.ok;

		$scope.confirm.bsObj = new bootstrap.Modal(document.getElementById('modal_confirm'), {
			keyboard: false
		});
		
		$scope.confirm.bsObj.show();
	}
	
	/*
	 * 加载单选弹出框列表数据
	 */
	$scope.radio.loadModalRadioGrid = function(pageNo) {
		console.log('-------$scope.radio.conditions---------', $scope.radio.conditions);
		$http.post($scope.radio.pathGridRequest, {}, {params: {page: pageNo, size: $scope.radio.pagination.currentSize, conditionss: JSON.stringify($scope.radio.conditions)}})
		.success(function (response) {
			if(response.code == 0) {
				console.log(response);
				$scope.radio.pagination.currentPage = pageNo;
				
				$scope.radio.rows = response.data;
				
				// 更新分页数据
				$scope.radio.pagination.totalNum = response.count;
				$scope.radio.pagination.totalPage = Math.floor(($scope.radio.pagination.totalNum + $scope.radio.pagination.currentSize - 1) / $scope.radio.pagination.currentSize);
				for(var i = 0; i < 5 && i < $scope.radio.pagination.totalPage; i++) {
					if($scope.radio.pagination.currentPage < 3) {
						$scope.radio.pagination.pagerArr[i].num = i + 1;
					} else if($scope.radio.pagination.currentPage > $scope.radio.pagination.totalPage - 3) {
						$scope.radio.pagination.pagerArr[i].num = $scope.radio.pagination.totalPage - 4 + i;
					} else {
						$scope.radio.pagination.pagerArr[i].num = $scope.radio.pagination.currentPage - 2 + i;
					}
				}
			}
		});
	}
	
	/*
	 * 清空复选款搜索条件
	 */
	$scope.radio.clearConditions = function() {
		for (var i = 0; i < $scope.radio.conditions.length; i++) {
			$scope.radio.conditions[i].value = '';
		}
	}
	
	/*
	 * 显示弹出框(下拉选择)
	 */
	$scope.showModalDropdown = function(config) {
//		$scope.dropdown.tip = config.tip;
//		$scope.dropdown.ok = config.ok;

		$scope.dropdown.bsObj = new bootstrap.Modal(document.getElementById('modal_dropdown'), {
			keyboard: false
		});
		
		$scope.dropdown.bsObj.show();
	}
	
	/*
	 * 加载复选款待选数据
	 */
	$scope.checkbox.loadModalCheckboxGrid = function(pageNo) {
		console.log('-------$scope.checkbox.conditions---------', $scope.checkbox.conditions);
		$http.post($scope.checkbox.pathGridRequest, {}, {params: {page: pageNo, size: $scope.checkbox.pagination.currentSize, conditionss: JSON.stringify($scope.checkbox.conditions)}})
		.success(function (response) {
			if(response.code == 0) {
				console.log(response);
				$scope.checkbox.pagination.currentPage = pageNo;
				
				$scope.checkbox.rows = response.data;
				
				// 更新分页数据
				$scope.checkbox.pagination.totalNum = response.count;
				$scope.checkbox.pagination.totalPage = Math.floor(($scope.checkbox.pagination.totalNum + $scope.checkbox.pagination.currentSize - 1) / $scope.checkbox.pagination.currentSize);
				for(var i = 0; i < 5 && i < $scope.checkbox.pagination.totalPage; i++) {
					if($scope.checkbox.pagination.currentPage < 3) {
						$scope.checkbox.pagination.pagerArr[i].num = i + 1;
					} else if($scope.checkbox.pagination.currentPage > $scope.checkbox.pagination.totalPage - 3) {
						$scope.checkbox.pagination.pagerArr[i].num = $scope.checkbox.pagination.totalPage - 4 + i;
					} else {
						$scope.checkbox.pagination.pagerArr[i].num = $scope.checkbox.pagination.currentPage - 2 + i;
					}
				}
			}
		});
	}
	
	/*
	 * 加载复选款已选中数据
	 */
	$scope.checkbox.loadModalCheckboxRight = function(listUkey) {
		var indexOfLoading = layer.load(1, {shade: [0.5,'#000000']});
		$http.post($scope.checkbox.pathGridRequest, {}, {params: {page: 1, size: 999, ukey: $scope.checkbox.ukey, listUkey: listUkey}})
		.success(function (response) {
			if(response.code == 0) {
				console.log('-------$scope.checkbox.rowsSelected----response---', response);
				$scope.checkbox.rowsSelected = response.data;
			}
			layer.closeAll();
		});
	}
	
	/*
	 * 清空复选款搜索条件
	 */
	$scope.checkbox.clearConditions = function() {
		for (var i = 0; i < $scope.checkbox.conditions.length; i++) {
			$scope.checkbox.conditions[i].value = '';
		}
	}
	
	/*
	 * 加载多文件附件数据
	 */
	$scope.multy.loadModalMulty = function() {
		var indexOfLoading = layer.load(1, {shade: [0.5,'#000000']});
		$http.post('/api/inter/tbFileInfo/search', {}, {params: {page: 1, size: 999, sourceId: $scope.multy.sourceId, sourceType: $scope.multy.sourceType, sourceCode: $scope.multy.sourceCode}})
		.success(function (response) {
			if(response.code == 0) {
				console.log('-------$scope.multy.rows----', $scope.multy.rows);
				$scope.multy.rows = response.data;
        		$scope.valueMap[$scope.multy.sourceCode] = $scope.multy.rows.length + '个附件';
			}
			layer.closeAll();
		});
	}
	
	/*
	 * 加载确认框
	 */
	$scope.confirm.loadModalConfirm = function(tip) {
		$scope.confirm.bsObj = new bootstrap.Modal(document.getElementById('modal_confirm'), {
			keyboard: false
		});
		
		$scope.confirm.tip = tip;
		
		$scope.confirm.bsObj.show();
	}
	
	/*
	 * 保存前验证表单
	 */
	$scope.doCheckFormBeforeSave = function() {
		$scope.form.checked = true; // 表单是否已验证
		for (var i = 0; i < $scope.rows.length; i++) {
			var row = $scope.rows[i];
			var value = $scope.valueMap[row.code];
			if (row.required == 1 && (value == null || value == undefined || value === '')) {
				return false;
			}
		}
		return true;
	}
	
	$scope.doSave = function() {
		var data = $scope.valueMap;
		
		var checkResult = $scope.doCheckFormBeforeSave();
		console.log('checkResult---', checkResult);
		if (checkResult == false) {
			return;
		}
		data.subData = JSON.stringify($scope.subGrid.sonlist);
		console.log('----------$scope.valueMap---------', $scope.valueMap);
		console.log('----------$scope.subData---------', $scope.subGrid.sonlist);
		var indexOfLoading = layer.load(1, {shade: [0.5,'#000000']})
		$http.post($scope.saveBtn.pathCommit, {}, {params: data})
		.success(function (response) {
			if(response.code == 0) {
				layer.msg(response.msg);
				var code = response.data.code;
				if(code == 1) {
					setTimeout(function(){
						window.location.href = response.data.url;
					}, 1000);
				} else if(code == 2) {
					setTimeout(function(){
						window.parent.bsModalLinkObj.hide();
						window.parent.location.reload();
					}, 1000);
				} else if(code == 3) {
					setTimeout(function(){
						window.location.reload();
					}, 1000);
				} else if(code == 4) {
					setTimeout(function(){
						window.parent.bsModalLinkObj.hide();
					}, 1000);
				}
			} else {
				layer.closeAll();
				layer.msg(response.msg);
			}
		});
	}
	
	$scope.doFlowPass = function() {
		var indexOfLoading = layer.load(1, {shade: [0.5,'#000000']});
		$http.post($scope.flowPassBtn.pathCommit, {}, {params: $scope.valueMap})
		.success(function (response) {
			if(response.code == 0) {
				setTimeout(function(){
					window.location.reload();
				}, 1000);
			} else {
				layer.closeAll();
				layer.msg(response.msg);
			}
		});
	}
	
	$scope.doFlowRefuse = function() {
		var indexOfLoading = layer.load(1, {shade: [0.5,'#000000']});
		$http.post($scope.flowRefuseBtn.pathCommit, {}, {params: $scope.valueMap})
		.success(function (response) {
			if(response.code == 0) {
				setTimeout(function(){
					window.location.reload();
				}, 1000);
			} else {
				layer.closeAll();
				layer.msg(response.msg);
			}
		});
	}
	
	$scope.doFlowInit = function() {
		var indexOfLoading = layer.load(1, {shade: [0.5,'#000000']});
		$http.post($scope.flowInitBtn.pathCommit, {}, {params: $scope.valueMap})
		.success(function (response) {
			if(response.code == 0) {
				setTimeout(function(){
					window.location.reload();
				}, 1000);
			} else {
				layer.closeAll();
				layer.msg(response.msg);
			}
		});
	}
	
	$scope.doFlowLog = function() {
		$scope.showModalLink('/web/flow/ysp/toAudit?bid=' + $scope.valueMap['bid'], '流程跟踪');
	}
	
	$scope.doDelete = function() {
		$http.post($scope.deleteBtn.pathCommit, {}, {params: $scope.valueMap})
		.success(function (response) {
			if(response.code == 0) {
				
			} else {
				layer.msg(response.msg);
			}
		});
	}
	
	/*
	 * 获取选中的子列表数据
	 */
	$scope.getSelectedSonlist = function() {
		var rows = [];
		for(var i = 0; i < $scope.subGrid.sonlist.length; i++) {
			if ($scope.subGrid.sonlist[i].checked) {
				rows.push($scope.subGrid.sonlist[i]);
			}
		}
		return rows;
	}
	
	$scope.modalLink = {} // 链接弹出框
	
	/*
	 * 显示
	 */
	$scope.showModalLink = function(url, title) {
		$scope.modalLink.bsObj = window.bsModalLinkObj
		document.getElementById('modal_link_iframe').src = url;
		$scope.modalLink.title = title;
		$scope.modalLink.bsObj.show();
	}
	
	/*
	 * 格式化浮点数
	 */
	$scope.toFix = function(number, precision) {
		if (Number.isInteger(Number(number))) {
			return number;
		}
		number = Math.round(+number + 'e' + precision) / Math.pow(10, precision) + '';
		let s = number.split('.');
		if ((s[1] || '').length < precision) {
			s[1] = s[1] || '';
			s[1] += new Array(precision - s[1].length).fill('0').join('');
		}
		return s.join('.');
	}
}